package controller;

import org.apache.commons.lang3.RandomStringUtils;
import util.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * @author 高杰  gao4433@qq.com
 * @Description
 * @date 2021/12/16 16:21
 * @since 1.8
 */
@MultipartConfig(
        // 上传的文件保存的具体位置
        location = "D:\\Desktop\\upload-images",
        // 最大支持的文件上限（单位：字节）
        maxFileSize = 100 * 1024 * 1024,
        // 最大支持的请求上限（单位：字节），要求：maxRequestSize >= maxFileSize
        maxRequestSize = 104857600
)
public class GoodsAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("n");
        String price = request.getParameter("p");
        // 获取来自前端提交的图片文件
        Part image = request.getPart("i");
        // 获取来自前端提交的图片的原始名称
        String fileName = image.getSubmittedFileName();
        // 将名称以 . 进行切割
        String[] strings = fileName.split("\\.");
        // 获取文件的后缀名
        String suffix = strings[1];
        // 为上传的图片设置新名称
        String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;
        // 将提交的图片文件保存到磁盘
        image.write(img);

        String sql = "INSERT INTO `goods` (`name`,`price`,`image`) VALUES(?,?,?)";
        JdbcUtils.modify(sql,name,price,img);

        response.sendRedirect("/goods-list.jsp");

    }
}



